﻿using System;
using System.Configuration;
using System.Collections.Generic;
using System.Windows;
using System.Drawing;
using Uniloader.Managers;
using Uniloader.Configuration;

namespace XamlTorrent
{
    /// <summary>
    /// Entry point for the XamlTorrent application.
    /// </summary>
    public partial class App : Application
    {
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            InitTrayIcon();
            InitDownloadManagers();
        }

        private void Application_Exit(object sender, ExitEventArgs e)
        {
            DisposeTrayIcon();
            DisposeDownloadManagers();

            // Save the settings before exiting...
            XamlTorrent.Properties.Settings.Default.Save();
        }

        public IList<TransferManager> DownloadManagers
        {
            get { return downloadManagersWrapper; }
        }

        #region Download Manager
        List<TransferManager> downloadManagers;
        IList<TransferManager> downloadManagersWrapper;
        //List<CreateTaskUIElement> createTaskUI;

        /// <summary>
        /// Loads download managers specified in configuration.
        /// </summary>
        private void InitDownloadManagers()
        {
            downloadManagers = new List<TransferManager>();
            downloadManagersWrapper = downloadManagers.AsReadOnly();
            //createTaskUI = new List<CreateTaskUIElement>();

            // Load the app.config file
            System.Configuration.Configuration exeConfig =
                ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            
            // Read the <uniloaderLibraries /> config section 
            UniloaderLibrariesGroup managersGroup =
                exeConfig.GetSectionGroup(UniloaderLibrariesGroup.SectionGroupName) as UniloaderLibrariesGroup;

            if (managersGroup != null)
            {
                foreach (TransferManagerSection managerSection in managersGroup.Sections)
                {
                    if (managerSection == null) continue; // can't understand this section

                    try
                    {
                        LoadManagerConfigSection(managerSection);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message,
                            String.Format("Error loading \"{0}\"", managerSection.DisplayName), 
                            MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
            }

            if(downloadManagers.Count == 0)
                MessageBox.Show("No transfer managers have been loaded.",
                    "No transfer managers loaded", 
                    MessageBoxButton.OK, MessageBoxImage.Warning);
        }

        private void LoadManagerConfigSection(TransferManagerSection managerSection)
        {
            if (managerSection.ManagerType == null)
                throw new ConfigurationErrorsException(String.Format(
                    "Unable to load transmssion manager \"{0}\": the type was not found.", managerSection.DisplayName
                    ));

            TransferManager downloadManager = 
                (TransferManager)Activator.CreateInstance(managerSection.ManagerType, managerSection);

            downloadManagers.Add(downloadManager); // add instance to the list

            // Register the UI types.
            //foreach (CreateTaskUIElement elem in managerSection.CreateTaskUIs)
            //{
            //    createTaskUI.Add(elem);
            //}
            // Can't use AddRange() because ConfigurationElementCollection is not a generic
        }

        private void DisposeDownloadManagers()
        {
            if (downloadManagers != null)
            {
                foreach (IDisposable manager in downloadManagers)
                {
                    manager.Dispose();
                }
            }
        } 
        #endregion

        #region System Tray Icon
        //System.Windows.Forms.NotifyIcon trayIcon;

        private void InitTrayIcon()
        {
            //Uri trayIconUri = new Uri("Images/XamlTorrent.ico", UriKind.Relative);

            //trayIcon = new System.Windows.Forms.NotifyIcon();
            //trayIcon.Icon = new Icon(Application.GetResourceStream(trayIconUri).Stream);
            //trayIcon.Visible = true;
        }

        private void DisposeTrayIcon()
        {
            //if (trayIcon != null)
            //    trayIcon.Visible = false;
        } 
        #endregion
    }
}
